﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Security.Permissions;
using System.Web.UI.HtmlControls;

namespace jQuery.WebControls.UI
{
    /// <summary>
    /// Control Panel que se muestra como el PopUp flotante.
    /// </summary>
    [AspNetHostingPermission(SecurityAction.Demand,
        Level = AspNetHostingPermissionLevel.Minimal),
    AspNetHostingPermission(SecurityAction.InheritanceDemand,
        Level = AspNetHostingPermissionLevel.Minimal)]
    [DefaultProperty("MessageTitle")]
    [ToolboxData("<{0}:PopUpPanel runat=server></{0}:PopUpPanel>")]
    public class PopUpPanel : Panel
    {
        private ClientScriptProxy scriptManager;
        private jQueryScriptManager jQueryMngr;
        private bool vCloseOnEscape;

        private ClientScriptProxy ClientScriptProxy
        {
            get
            {
                if (scriptManager == null)
                {
                    scriptManager = ClientScriptProxy.Current;
                }
                return scriptManager;
            }
        }
        /// <summary>
        /// Evento que se ejecuta cuando se carga la página. Se comprueba los estilos y jquery necesarios
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            if (!Page.IsPostBack)
            {
                if (!DesignMode)
                    CheckQueryManager();                
            }           
            ClientScriptProxy.RegisterStartupScript(Page, GetType(), String.Format("PP{0}", ClientID), Script(), true);
        }       

        #region PROPIEDADES
        /// <summary>
        /// MessageTitle de la ventana flotante
        /// </summary>
        [Bindable(true)]
        [Category("Appearance")]
        [DefaultValue("")]
        [Localizable(true)]
        public string MessageTitle
        {
            get
            {                
                return ToolTip;
            }
            set
            {
                ToolTip = value;
            }
        }
        
        /// <summary>
        /// Obtiene o establece si el PopUpPanel se puede redimensionar o no
        /// </summary>
        [Category("Appearance")]
        [DefaultValue(true)]
        [Description("Propiedad que indica si se puede redimiensionar el PopUpPanel. Por defecto es true")]
        public bool Resizable
        {
            get
            {

                if (ViewState["rdable"] == null)
                {
                    ViewState.Add("rdable", true);
                }
                return bool.Parse(ViewState["rdable"].ToString());
            }
            set
            {
                ViewState["rdable"] = value;
            }
        }
        /// <summary>
        /// Obtiene o establece si el PopUpPanel se puede redimensionar o no
        /// </summary>
        [Category("Appearance")]
        [DefaultValue(true)]
        [Description("Propiedad que indica si se muestra el botón en forma de X para cerrar el popup. Por defecto es true")]
        public bool ShowCloseButton
        {
            get
            {

                if (ViewState["vbc"] == null)
                {
                    ViewState.Add("vbc", true);
                }
                return bool.Parse(ViewState["vbc"].ToString());
            }
            set
            {
                ViewState["vbc"] = value;
            }
        }       
        /// <summary>
        /// Obtiene o establece el ancho del PopUpPanel. Por defecto, 500px
        /// </summary>
        [DefaultValue("500px")]
        [Category("Appearance")]
        [Description("Ancho del pop-up")]
        public override Unit Width
        {
            get { return (base.Width == null || base.Width.Value == 0 ? new Unit(500, UnitType.Pixel) : base.Width); }
            set { base.Width = value; }
        }

        [DefaultValue("true")]
        [Category("Appearance")]
        [Description("Muestra el pop-up como una ventana de diálogo modal")]
        public bool Modal
        {
            get 
            {
                if (ViewState["modal"] == null)
                    return true;
                else
                    return bool.Parse(ViewState["modal"].ToString());
            }
            set
            {
                ViewState["modal"] = value;
            }
        }

        [DefaultValue("true")]
        [Category("Appearance")]
        [Description("Indica si se puede mover o no la ventana de diálogo")]
        public bool Draggable
        {
            get
            {
                if (ViewState["dg"] == null)
                    return true;
                else
                    return bool.Parse(ViewState["dg"].ToString());
            }
            set
            {
                ViewState["dg"] = value;
            }
        }

        /// <summary>
        /// Gets or sets the X axe position where the dialog will be displayed
        /// </summary>
        [DefaultValue("PositionsX.Center")]
        [Category("Appearance")]
        [Description("Gets or sets the X axe position where the dialog will be displayed")]
        public PositionsX PositionX
        {
            get
            {
                if (ViewState["X"] != null)
                {
                    return (PositionsX)ViewState["X"];
                }
                else
                {
                    return PositionsX.Center;
                }
            }
            set
            {
                ViewState["X"] = value;
            }
        }

        /// <summary>
        /// Gets or sets the Y axe position where the dialog will be displayed
        /// </summary>
        [DefaultValue("PositionsX.Center")]
        [Category("Appearance")]
        [Description("Gets or sets the Y axe position where the dialog will be displayed")]
        public PositionsY PositionY
        {
            get
            {
                if (ViewState["Y"] != null)
                {
                    return (PositionsY)ViewState["Y"];
                }
                else
                {
                    return PositionsY.Center;
                }
            }
            set
            {
                ViewState["Y"] = value;
            }
        }
        [DefaultValue("PositionsX.Center")]
        [Category("Appearance")]
        [Description("Gets or sets if the dialog must be close when Escape is pressed")]
        public bool CloseOnEscape
        {
            get
            {
                return vCloseOnEscape;
            }
            set
            {
                vCloseOnEscape = value;
            }
        }
        #endregion
        
        /// <summary>
        /// Genera la salida javascript en jQuery para inciar el PopUpPanel
        /// </summary>
        /// <returns></returns>
        private string Script()
        {
            
            string clientIDParent = Page.Form.ClientID;
            string txtScript = "";
            
            txtScript += "$('#" + ClientID + "').dialog({ ";
            txtScript += "closeOnEscape: " + CloseOnEscape.ToString().ToLower() + ",";
            txtScript += "draggable: " + Draggable.ToString().ToLower() + "";
            if (!ShowCloseButton)
            {
                txtScript += ", open: function(event, ui) { jQuery('.ui-dialog-titlebar-close').hide(); }";
            }
            if (PositionX != PositionsX.Center || PositionY != PositionsY.Center)
            {
                txtScript += ", position: ['" + PositionX.ToString().ToLower() + "','" + PositionY.ToString().ToLower() + "']";
            }
            //txtScript += ", close: function (event, ui) { $('#" + clientIDParent + "').append($('#" + ClientID + "').parent()); }";
            txtScript += getStyleDialog();
            txtScript += ", modal:" + Modal.ToString().ToLower();
            txtScript += ", width: " + Width.Value.ToString();
            txtScript += ", resizable: " + Resizable.ToString().ToLower() + "}); ";

            //if (Modal)
            //{
                
            //}
            //else
            //{
            //    string addToPostBack = string.Format("addTPB_{0}", ClientID);

            //    txtScript += addToPostBack + "= function (func) {";
            //    txtScript += "    var old__doPostBack = __doPostBack;";
            //    txtScript += "    if (typeof __doPostBack != 'function') {";
            //    txtScript += "        __doPostBack = func;";
            //    txtScript += "    } else {";
            //    txtScript += "        __doPostBack = function (t, a) {";
            //    txtScript += "            if (func(t, a)) old__doPostBack(t, a);";
            //    txtScript += "        }";
            //    txtScript += "    }";
            //    txtScript += "};";
            //    txtScript += "$(document).ready(function () {   ";        
            //    txtScript +=     addToPostBack + "(function (t, a) {";
            //    txtScript += "        $('#" + clientIDParent + "').append($('#" + ClientID + "').parent());";
            //    txtScript += "        return true;";
            //    txtScript += "    });";
            //    txtScript += "});";                
            //}
            if(Modal)
                txtScript += "$('.ui-widget-overlay.ui-front').appendTo($('form:first'));";
            txtScript += "$('#" + ClientID + "').parent().appendTo($('form:first'));";
            
            return txtScript;
        }

        private string getStyleDialog()
        {
            string style = "";
            if (!Height.IsEmpty)
                style += String.Format(",height: {0}", Height.Value.ToString());
            if (!Width.IsEmpty)
                style += String.Format(",width: {0}", Width.Value.ToString());

            return (!String.IsNullOrEmpty(style) ? style : String.Empty);
        }

        //private string GetParentClientID()
        //{
        //    Control parent = this.Parent as Control;
        //    string parentID = this.ClientID;
        //    while (parent != null)
        //    {
        //        if (parent.GetType().FullName.Contains("UpdatePanel") || 
        //            parent.GetType().FullName.Contains("Form"))
        //        {
        //            parentID = parent.ClientID;
        //            break;
        //        }                
        //        parent = parent.Parent as Control;
        //    }

        //    return parentID;
        //}

        private jQueryScriptManager jQueryManager
        {
            get
            {
                if (jQueryMngr == null)
                    jQueryMngr = Common.Instance.Get_jQueryScriptManager(Page);
                return jQueryMngr;
            }
        }

        private void CheckQueryManager()
        {
            jQueryScriptManager aux = jQueryManager;
        }
    }
}
